import 'package:architecture/os_size.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:study_demo/db/isar.dart';

import '../../../base/theme_controller.dart';
import '../../../util/common.dart';
import '../../../widgets/popup.dart';
import '../../../widgets/yz_text.dart';
import 'api_tool_controller.dart';

class ApiToolPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetX<ApiToolController>(
        init: ApiToolController(),
        builder: (controller) {
          return Scaffold(
              appBar: AppBar(
                title: Text('api工具'),
                actions: [
                  TextButton(
                      onPressed: () {
                        controller.save();
                      },
                      child: Text(
                        '保存',
                        style: TextStyle(color: Colors.white),
                      ))
                ],
              ),
              body: Container(
                  margin: EdgeInsets.symmetric(vertical: 10),
                  child: Column(children: [
                    Row(
                      children: [
                        _requestMethod(controller),
                        _url(controller),
                        textButton('发送', onPressed: () {
                          controller.send();
                        }),
                        Offstage(
                            offstage: controller.statusCode.value == 0,
                            child: Row(
                              children: [
                                Text('状态码：'),
                                Text(
                                  controller.statusCode.value.toString(),
                                  style: TextStyle(
                                      color: controller.statusCode.value == 200
                                          ? Colors.green
                                          : Colors.red,
                                      fontWeight: FontWeight.bold),
                                )
                              ],
                            )),
                      ],
                    ),
                    Expanded(
                        child: Row(
                      children: [
                        _apiList(controller),
                        Container(
                            width: windowWidth / 4,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                // Container(
                                //     width: windowWidth/2,
                                //     height: 1, color: Colors.grey.withOpacity(0.5)),
                                // _requestInfo(),
                                _tabBar(controller),
                                Offstage(
                                    offstage: controller.type.value == 1,
                                    child: Container(
                                        margin: EdgeInsets.only(left: 15),
                                        child: Text(
                                          '参数列表',
                                          style: TextStyle(fontSize: 13),
                                        ))),
                                Offstage(
                                    offstage: controller.type.value != 1,
                                    child: _requestBody(controller))
                              ],
                            )),
                        Expanded(
                            child: Container(
                                margin: EdgeInsets.only(left: 15),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: [
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        MyTextField(
                                          controller: controller
                                              .classNameTextEditingController,
                                          width: 100,
                                          height: 30,
                                          hintText: '类名',
                                          margin: EdgeInsets.only(bottom: 10),
                                        ),
                                        Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.end,
                                          children: [
                                            _iconButton(
                                              Icons.cleaning_services_rounded,
                                              onPressed: () {
                                                controller.clearResult();
                                              },
                                            ),
                                            _iconButton(
                                              Icons.copy,
                                              onPressed: () {
                                                controller.copyResult();
                                              },
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                    Expanded(
                                        child: TextField(
                                      controller: controller
                                          .resultTextEditingController,
                                      readOnly: true,
                                      decoration: InputDecoration(
                                        contentPadding: EdgeInsets.all(10),
                                        border: const OutlineInputBorder(),
                                      ),
                                      maxLines: 30,
                                      style: textStyle1,
                                    )),
                                  ],
                                ))),
                        SizedBox(
                            width: 30,
                            child: IconButton(
                                onPressed: () {
                                  controller.transform();
                                },
                                icon: Icon(Icons
                                    .keyboard_double_arrow_right_rounded))),
                        Expanded(
                            child: Container(
                                margin: EdgeInsets.symmetric(horizontal: 10),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: [
                                    Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        _iconButton(
                                          Icons.cleaning_services_rounded,
                                          onPressed: () {
                                            controller.clearModel();
                                          },
                                        ),
                                        _iconButton(
                                          Icons.copy,
                                          onPressed: () {
                                            controller.copyAll();
                                          },
                                        ),
                                      ],
                                    ),
                                    Expanded(
                                      child: TextField(
                                          controller: controller
                                              .modelTextEditingController,
                                          readOnly: true,
                                          decoration: InputDecoration(
                                            contentPadding: EdgeInsets.all(10),
                                            border: const OutlineInputBorder(),
                                          ),
                                          maxLines: 30,
                                          style: TextStyle(
                                              color: Colors.blue,
                                              fontWeight: FontWeight.normal)),
                                    ),
                                  ],
                                )))
                      ],
                    ))
                  ])));
        });
  }

  _requestMethod(ApiToolController controller) {
    return Container(
      width: 80,
      margin: EdgeInsets.only(left: 15),
      alignment: Alignment.center,
      child: DropdownButton<String>(
        isExpanded: true,
        icon: Icon(Icons.arrow_drop_down_rounded),
        underline: Container(height: 1, color: Colors.grey.withOpacity(0.5)),
        value: controller.requestMethod.value,
        style: TextStyle(fontSize: 16, color: Colors.green.withAlpha(180)),
        onChanged: (String? newValue) {
          controller.requestMethod.value = newValue!;
        },
        items: controller.requestMethods
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(
              value.toString(),
              textAlign: TextAlign.right,
            ),
          );
        }).toList(),
      ),
    );
  }

  _url(ApiToolController controller) {
    return MyTextField(
      controller: controller.urlEditingController,
      width: windowWidth * 0.4,
      height: 70,
      hintText: '请输入url',
      iconRight: IconButton(
          onPressed: () {
            controller.clearUrl();
          },
          icon: Icon(
            Icons.clear,
            size: 20,
          )),
      margin: EdgeInsets.only(left: 15),
    );
  }

  _tabBar(ApiToolController controller) {
    return PreferredSize(
        preferredSize: Size.fromHeight(48),
        child: Material(
          color: Colors.transparent,
          child: TabBar(
            controller: controller.tabController,
            tabs: [
              // Tab(
              //   child: Text('参数'),
              // ),
              Tab(
                child: Text('请求头'),
              ),
              Tab(
                child: Text('请求体'),
              ),
            ],
          ),
        ));
  }

  _text(String text) {
    return Text(
      text,
      style: TextStyle(color: Colors.grey),
    );
  }

  _list(ApiToolController controller) {
    return Expanded(
        child: ListView.separated(
      itemCount: 5,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {},
          child: itemLayout(index, controller),
        );
      },
      separatorBuilder: (context, index) {
        return Divider(
          height: 3,
          color: Colors.transparent,
        );
      },
    ));
  }

  itemLayout(int index, ApiToolController controller) {
    return Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.fromLTRB(15, 0, 20, 0),
        height: 30,
        width: windowWidth * 0.35,
        child: Row(
          children: [
            Text(
              'key值',
              style: TextStyle(
                  color: Colors.blueAccent, fontWeight: FontWeight.bold),
            ),
            SizedBox(
              width: 30,
            ),
            Text(
              'value值',
              style: TextStyle(color: Colors.black),
            ),
          ],
        ));
  }

  _requestBody(ApiToolController controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        MyTextField(
          controller: controller.contentEditingController,
          width: 300,
          height: windowHeight * 0.55,
          hintText: '',
          maxLines: 100,
          iconRight: _iconButton(Icons.clear, onPressed: () {
            controller.contentEditingController.clear();
          }),
          margin: EdgeInsets.only(top: 15, left: 15),
          contentPadding: EdgeInsets.all(15),
        ),
        TextButton(
            onPressed: () {
              controller.format();
            },
            child: Text(
              '格式化',
              style: TextStyle(color: Colors.blueAccent),
            )),
      ],
    );
  }

  _apiList(ApiToolController controller) {
    return Container(
        width: windowWidth * 0.1,
        child: ListView.separated(
          itemCount: controller.apiInfoList.length,
          itemBuilder: (context, index) {
            final item = controller.apiInfoList[index];
            return _itemApiLayout(item, controller);
          },
          separatorBuilder: (context, index) {
            return Divider(
              height: 3,
              color: Colors.transparent,
            );
          },
        ));
  }

  _itemApiLayout(ApiInfo apiInfo, ApiToolController controller) {
    double globPositionX = 0;
    double globPositionY = 0;
    return Listener(
        onPointerMove: (movePointEvent) {},
        child: GestureDetector(
            onTap: () {
              controller.chooseApi(apiInfo);
            },
            onLongPress: () {
              Navigator.of(Get.context!).push(PopupWindow(
                  child: Container(
                      height: 32,
                      width: 60,
                      color: Color(0xffEBE8E8),
                      child: TextButton(
                          onPressed: () {
                            Get.back();
                            controller.deleteApi(apiInfo.name!);
                          },
                          child: Text(
                            '删除',
                            style: TextStyle(color: Colors.black, fontSize: 14),
                          ))),
                  left: globPositionX + 25,
                  top: globPositionY));
            },
            onPanDown: (DragDownDetails details) {
              details.globalPosition.dx - 5;
              globPositionY = details.globalPosition.dy + 10;
            },
            child: Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.fromLTRB(15, 0, 20, 0),
                height: 30,
                width: windowWidth * 0.15,
                child: Row(
                  children: [
                    Text(
                      apiInfo.name!,
                      style: TextStyle(
                          color: Colors.blueAccent,
                          fontWeight: FontWeight.bold),
                    ),
                  ],
                ))));
  }

  _iconButton(IconData icon, {Function? onPressed}) {
    return IconButton(
      icon: Icon(
        icon,
        size: 20,
      ),
      onPressed: () {
        onPressed?.call();
      },
    );
  }
}
